// charts的控制器
angular.module('detailaccountChoose.controller', ['detailaccountChoose.service'])

  .controller('DetailaccountChooseCtrl', function ($scope, ionicDatePicker,$ionicModal,$rootScope,$http,$state,$filter,$timeout) {

//配置时间日历
    var start = {
      callback: function (val) {  //Mandatory
        console.log('Return value from the datepicker popup is : ' + val, new Date(val));
          $scope.st =val;
          console.log(val)
        $scope.starttime = $filter("date")(new Date(val), "yyyy-MM-dd");


      },
      disabledDates: [ ],           //Optional
      from: new Date(2000, 1, 1), //Optional
      to: new Date(2128, 10, 30), //Optional
      inputDate: new Date(),      //Optional
      mondayFirst: true,          //Optional
      disableWeekdays: [""],       //Optional
      closeOnSelect: false,       //Optional
      templateType: 'popup'       //Optional
    };
    $scope.start = function () {
      ionicDatePicker.openDatePicker(start);
    };
    var end = {
      callback: function (val) {  //Mandatory
          $scope.endtimer = $filter("date")(new Date(val), "yyyy-MM-dd");
          $scope.et=val;
          console.log($scope.st);
          console.log($rootScope.et);
          if($scope.et - $scope.st < 0){
              alert('日期输入错误，开始时间必须小于结束时间');
              console.log('日期输入错误，开始时间必须小于结束时间');
              $scope.endtimer=""
          }

      },
      disabledDates: [            //Optional
      ],
      from: new Date(2000, 1, 1), //Optional
      to: new Date(2128, 10, 30), //Optional
      inputDate: new Date(),      //Optional
      mondayFirst: true,          //Optional
      disableWeekdays: [""],       //Optional
      closeOnSelect: false,       //Optional
      templateType: 'popup'       //Optional
    }



    $scope.end = function () {
      ionicDatePicker.openDatePicker(end);
    };




//选择三个和一个月
    $scope.month = function (num) {
      var now = $filter("date")(new Date(), "yyyy-MM-dd");
        console.log(now);
        var pastyear = new Date().getFullYear();
      var pastmonth;
     var one=document.getElementsByClassName("month-one");
     var three=document.getElementsByClassName("month-three");

      if(num ==1){
        one[0].style.backgroundColor="#E9E0A9"
        three[0].style.backgroundColor="#ffffff"
      }else if(num ==3){
        three[0].style.backgroundColor="#E9E0A9"
        one[0].style.backgroundColor="#ffffff"
      }
      if (num == 1 || new Date().getMonth() !== 0) {
        pastmonth = new Date().getMonth()
      } else {
        pastmonth = 12;
      }
      if (num == 3) {
        switch (new Date().getMonth() - 2) {
          case 0:
            pastmonth = 12;
            break;
          case -1:
            pastmonth = 11;
            break;
          case -2:
            pastmonth = 10;
            break;
          default :
            pastmonth = new Date().getMonth() - 2;
            break;
        }
      }
      console.log(pastmonth);
      if (pastmonth > new Date().getMonth() + 1) {
        pastyear = pastyear - 1;
      }
        if(pastmonth<10){
            pastmonth="0"+pastmonth
        }
      var past = pastyear + "-" + pastmonth + "-" + new Date().getDate()
      var start = document.getElementsByClassName("start");
        var end = document.getElementsByClassName("end");
      start[0].innerHTML = past
      end[0].innerHTML = now

        //console.log(start[0].innerHTML);
        //console.log(end[0].innerHTML);
        $scope.past =past;
        $scope.now=now;
        console.log($scope.past);
        console.log($scope.now);
    }
        $timeout(function () {
            $scope.month(1);
        },100)



        //选择账户 模版控制
        //单选
        $scope.data = {
            clientSide: $scope.value,
        };

        $ionicModal.fromTemplateUrl('templates/chooseaccount.html', {
            scope: $scope
        }).then(function(modal) {
            $scope.modal = modal;
        });
        $scope.createContact = function() {
            $scope.modal.hide();
            $scope.value =$scope.data.clientSide
            $rootScope.acctName=$scope.data.clientSide


            console.log($scope.data.clientSide);

            angular.forEach($scope.clientSideList, function (item) {

            if(item.acctName==$scope.data.clientSide){
                $rootScope.acctNo=item.acctNo
                $rootScope.id =item.id
            }
            })

            //当前视图被销毁后，同时从内容中移除弹窗
            $scope.$on("$destroy", function () {
                $scope.modal.remove()
            })

        }
        console.log($rootScope.acctName);
        console.log($rootScope.acctNo);
        //接口
        var CCSessionId =localStorage.getItem("CCSessionId");
        var url =$rootScope.myglobal.serverurl+'/account/account/1.json?CCSessionId='+CCSessionId
        $http({
            method: "get",
            params:{
                innerVal:1,  //innerVal=1内2外
                //虚实都能查出来再加一个nominal:1
                acctType:2,
                //nominal:1
                //普通支付选付款方：innerVal:1 acctType:2
                //普通支付选收款方：innerVal:2 acctType:2
                //订单支付选付款方: innerVal:1 acctType:2 nominal:1
                //查明细选账户: innerVal:1 acctType:2
            },
            url:url,
        })
            .success(function(data){
                console.log(data);
                $scope.clientSideList=data;
            })
//按账户获取明细列表
        $scope.show = false;
        $scope.color = "#CD0A1B";

        $scope.detailaccount = function () {
            //设置查询按钮禁止点击，防止多次点击请求数据
            $scope.show =true;
            $scope.color="#666666"
            var CCSessionId=localStorage.getItem("CCSessionId");
            console.log(CCSessionId);
            var url =$rootScope.myglobal.serverurl+'/jymx/jymx.json?CCSessionId='+CCSessionId
            //获取选择时间
            var startDate = document.getElementsByClassName("start");
            var endDate = document.getElementsByClassName("end");
            //console.log(startDate);
            $scope.startDate= startDate[0].innerHTML
            $scope.endDate= endDate[0].innerHTML



            console.log($scope.startDate);
            console.log($scope.endDate);

            $http({
                method: "post",
                data:{
                    startDate:$scope.startDate,         //YYYY-MM-DD
                    endDate:$scope.endDate,           //要有默认值（最近一个月）
                    acctIds:$rootScope.id                //账户ID
                },
                url:url,
                transformRequest: $rootScope.post
            })
                .success(function(data){
                    //先判断msg是否为null或空，若是则给出提示并终止当前操作。
                    if(data.msg==null||data.msg==""){
                        alert("请选择账户和起止时间")
                        $scope.show = false;
                        $scope.color = "#CD0A1B";
                        console.log(data);
                        return false
                    }
                    //判断error是否为null或空，若是则给出提示,但继续读取details属性
                   else if(data.error==null||data.error==""){
                        //console.log(data);
                        //alert(data.msg)
                    }
                    //判断details是否为null或空或长度为0，,若是则给出提示”没有符合条件的交易记录”并终止操作.
                    if(data.details==null||data.details.length==0){
                            //console.log(data);
                            alert("没有符合条件的交易记录")
                        $scope.show = false;
                        $scope.color = "#CD0A1B";
                            return false
                        }else {


                            var subpaymentAmount=0;
                            var subcollectAmount=0;
                            var start=0;
                           $rootScope.detailaccountdata=data.details[0]
                        console.log($rootScope.detailaccountdata);
                        angular.forEach(data.details[0],function (item,index) {
                                //取details集合中最后一条记录中的amountBalance作为期末余额
                                if(index ==data.details[0].length-1){
                                    //console.log(item.amountBalance);//期末余额
                                    $scope.amountBalance=item.amountBalance
                                }
                                //取details集合中所有条记录中paymentAmount总和作为期总支出
                                subpaymentAmount+=item.paymentAmount*1000
                                //取details集合中所有条记录中collectAmount总和作为期总收入
                                subcollectAmount+=item.collectAmount*1000
                                ////对方账户号
                                //$rootScope.toAccountinfo.push(item.toAccount)
                                ////对方账户名称
                                //$rootScope.toAccountNameinfo.push(item.toAccountName)

                            })

                            //取（期末余额-期总收入+期总支出） 作为期初余额
                            start = $scope.amountBalance*1000-subcollectAmount+subpaymentAmount
                            //console.log(start/1000);
                            //账户名称
                            console.log($rootScope.acctName);
                            //账户
                            console.log($rootScope.acctNo);
                           //期末余额
                            $rootScope.detailaccountinfo.amountBalance= $scope.amountBalance;
                            //期总支出
                            $rootScope.detailaccountinfo.paymentAmount=subpaymentAmount/1000;
                            //期总收入
                            $rootScope.detailaccountinfo.collectAmount=subcollectAmount/1000;
                            //期初余额
                            $rootScope.detailaccountinfo.start=start/1000;

                        $state.go("tab.detailaccount")
                        $scope.show = false;




                        }


                    console.log(11);
                    console.log(data);

                    //跳转账户详细页面
                    //data.toAccount 对方账户号
                    //data.toAccountName 对方账户名称
                    //data.paymentAmount 支出金额
                    //data.collectAmount 收入金额
                    //data.transDate.time交易时间
                    //data.summary 备注


                })

        }






  })
